<?php
/*
 * Last Edited: 27-7-2013
*/
class IndexController extends Zend_Controller_Action
{
	//      Mang tham so nhan duoc o moi Action
	protected $_arrParam;
	protected $_host;
	protected $_user;
	var $mapCapdo = array(
			1 => array(
					"name" => "Nhập môn",
					"level" => 1,
					"max_star" => 3
			),
			2 => array(
					"name" => "Tập sự",
					"level" => 4,
					"max_star" => 4
			),
			3 => array(
					"name" => "Cao thủ",
					"level" => 8,
					"max_star" => 5
			),
			4 => array(
					"name" => "Cao cấp",
					"level" => 13,
					"max_star" => 7
			),
			5 => array(
					"name" => "Siêu cấp",
					"level" => 20,
					"max_star" => 9
			)
	);
	//var $logger;
	public function init()
	{
// 		$writer = new Zend_Log_Writer_Stream('/public/log/logfile');
// 		$this->logger = new Zend_Log($writer);
		
		$a = Zend_Auth::getInstance();
		$this->_user = $a->getIdentity();
		//      Load cac model can thiet
		Zend_Loader::loadClass("InputModel");

		//      Mang tham so nhan duoc o moi Action
		$this->_arrParam = $this->_request->getParams();

		//      Bo di cac truong ko can thiet
		unset($this->_arrParam['module']);
		unset($this->_arrParam['controller']);
		unset($this->_arrParam['action']);
		//      Them vao view cac chung
		$this->view->controller = $this->_request->getControllerName();
		$this->view->action = $this->_request->getActionName();
		$this->view->module = $this->_request->getModuleName();
		//      Loc cac bien dau vao
		foreach ($this->_arrParam as &$p) {
			$p = InputModel::standardInputString($p);
		}
	}

	public function preDispatch()
	{
		//      lay dia chi host
		$pageURL = 'http';
		if (!empty($_SERVER['HTTPS'])) {
			if ($_SERVER['HTTPS'] == 'on') {
				$pageURL .= "s";
			}
		}
		$pageURL .= "://";
		if ($_SERVER["SERVER_PORT"] != "80") {
			$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
		} else {
			$pageURL .= $_SERVER["SERVER_NAME"];
		}
		$this->_host = $this->view->host = $pageURL;
	}

	/*
	 *
	*/
	public function indexAction()
	{

	}

	/* Link goi tao tai khoan moi
	 *
	*/
	public function createAccountAction()
	{
		// Load model can thiet
		Zend_Loader::loadClass("UserModel");
		Zend_Loader::loadClass("RandomStringModel");

		//Lay va xu ly tham so
		$params = $this->_arrParam;
		if ($this->_request->isPost()) {
			if (isset($params['email']) && !empty($params['platform']) && !empty($params['user_name']) &&
			!empty($params['password'])) {
				$user_model = new UserModel();
				if (strlen($params['user_name']) >= 1 && strlen($params['user_name']) <= 12) {
					if (strlen($params['password']) >= 6 && strlen($params['password']) <= 50) {
						$result = $user_model->checkAccountExist($params['user_name'], $params['email']);
						if ($result) { // User moi
							$data = array(
									"user_name" => $params['user_name'],
									"password" => md5($params['password']),
									"email" => $params['email'],
									"user_gome" => 1000,
									"temp_gome" => 0,
									"is_vip" => 0,
									'daily_gift'=>date("Y-m-d", time()-86400),
									"status" => ACTIVE_STATUS);
							try {
								$id = $user_model->insert($data);
								if (!empty($params['email'])) {
									// Gui mail ve email nguoi dung de thong bao dang ki thanh cong neu co email gui len
									$html = "<div>Bạn đã đăng kí thành công tài khoản tại hệ thống game Zegome<br/>";
									$html .= "Tên tài khoản: " . $params['user_name'];
									$html .= "<br/><p align='center'><i>Liên hệ với chúng tôi: <b>Zero team</b><br/>";
									$html .= ADDRESS_ZEGOME . "<br/>";
									$html .= "Email: " . EMAIL_ZEGOME . " - Tel: " . PHONE_ZEGOME .
									".</i></p></div>";
									//      Gui mail
									$mail = new Zend_Mail('UTF-8');
									$mail->setBodyHtml($html);
									$mail->addTo($params['email']);
									$mail->addCc(EMAIL_ADMIN);
									$mail->setSubject('Đăng kí tài khoản tại hệ thống game Zegome');
									$mail->send();
								}
								$data = array("code"=>1,
										"content"=>"Success");
							}
							catch (exception $e) {
								$data = array("code"=>0,
										"content"=>"Error in server");
							}
						} else {
							$data = array("code"=>0,
									"content"=>"Duplicate data");
						}
					} else {
						$data = array("code"=>0,
								"content"=>"password ít nhất 6 kí tự");
					}
				} else {
					$data = array("code"=>0,
							"content"=>"user_name nhiều nhất là 12 kí tự");
				}
			} else {
				$data = array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}

	public function loginAction()
	{
		// Load model can thiet
		Zend_Loader::loadClass("UserModel");
		Zend_Loader::loadClass("GiftModel");
		Zend_Loader::loadClass("DailyGiftModel");
		Zend_Loader::loadClass("MessageModel");
		Zend_Loader::loadClass("AdvertiseModel");
		Zend_Loader::loadClass("RandomStringModel");

		//Lay va xu ly tham so
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (!empty($params['user_name']) && !empty($params['password']) && !empty($params['game_id']) &&
			isset($params['email']) && !empty($params['platform'])) {
				try {
					$user_model = new UserModel();
					// Tiền xử lý với những user bị block
					$result = $user_model->checkAccount($params);
					$message = "";
					if ($result) {
						if ($result['status'] == BLOCK_STATUS) {
							if (time() > $result['active_time']) {
								$user_model->update(array("status" => ACTIVE_STATUS), "user_id=" . $result['user_id']);
							} else {
								$message = "This account is temporarily blocked";
							}
						} else
						if ($result['status'] == DELETE_FOREVER_STATUS) {
							$message = "This account has been permanently deleted";
						}
					}
					if (empty($message)) {
						$result = $user_model->checkLogin($params);
						if ($result) { // User dang nhap thanh cong
							$a = Zend_Auth::getInstance();
							$this->_user = $a->getIdentity();
							$user = (object)$user_model->getUserInfo(array('user_id' => $this->_user->user_id, 'game_id' => $params['game_id']));
							$where = "user_id = " . $user->user_id;
							// Neu co email gui len thi xet
							if (!empty($params['email'])) {
								if (empty($user->email)) {
									$user_model->update(array("email" => $params['email']), $where);

									// Gui mail ve email nguoi dung de thong bao dang ki thanh cong neu co email gui len
									$html = "<div>Bạn đã đăng kí thành công tài khoản tại hệ thống game Zegome<br/>";
									$html .= "Tên tài khoản: " . $params['user_name'];
									$html .= "<br/><p align='center'><i>Liên hệ với chúng tôi: <b>Zegome team</b><br/>";
									$html .= ADDRESS_ZEGOME . "<br/>";
									$html .= "Email: " . EMAIL_ZEGOME . " - Tel: " . PHONE_ZEGOME .
									".</i></p></div>";
									//      Gui mail
									$mail = new Zend_Mail('UTF-8');
									$mail->setBodyHtml($html);
									$mail->addTo($params['email']);
									$mail->addCc(EMAIL_ADMIN);
									$mail->setSubject('Đăng kí tài khoản tại hệ thống game Zegome');
									$mail->send();
								}
							}
							$data = array();
							$data['code'] = 1;
							$content = array();
							$content['user_gome']=$user->user_gome;
							$content["level"] = $user->level;
							$content["total_win"] = $user->total_win;
							$content["total_lose"] = $user->total_lose;
							$content["achievement"] = $this->mapCapdo[$user->achievement_id]["name"];
							$content["star"] = $user->star;
							$content["max_star"] = $this->mapCapdo[$user->achievement_id]["max_star"];
							$content["experiment"] = $user->experiment;
							// Kiem tra hop qua tang xem co tin nhan ko?
							$message_model = new MessageModel();
							$list_message = $message_model->getList(array("user_id" => $user->user_id));
							$message = array();
							if (!empty($list_message) && count($list_message)) {
								foreach($list_message as $item){
									$message[] = array("message_content"=>$item['message'], "message_eng" => $item["message_eng"]);
								}
							}
							$content['message'] = $message;
							
							$advertise_model = new AdvertiseModel();
							$list_advertise = $advertise_model->getList();
							$advertise = array();
							if (!empty($list_advertise) && count($list_advertise)) {
								foreach($list_advertise as $item){
									$advertise[] = array(
												"icon"=>$item['icon'],
												"link" => $item["link"],
												"message_vn" => $item["message_vn"],
											 	"message_eng" => $item["message_eng"],		
									);
								}
							}
							$content['advertise'] = $advertise;

							// Kiem tra hop qua tang xem co qua tang ko?
							$gift_model = new GiftModel();
							$list_gift = $gift_model->getList($params);
							$gift = array();
							if (!empty($list_gift) && count($list_gift)) {
								foreach($list_gift as $item){
									$user_send_name = ($item['user_send_name'] == "1") ? "Hệ thống Zegome" :
									$item['user_send_name'];
									$array = array("gift_id"=>$item['id'],
											"user_send"=>$user_send_name,
											"zegome_gold"=>$item['zegome_gold'],
											"coupon"=>$item['coupon'],
											"message"=>$item['message']);
									$gift[] = $array;
								}
							}
							$content['gift'] = $gift;
							$data['content'] = $content;

							// Kiem tra xem co qua tang hang ngay ko?
							$daily_gift = array();
							if($user->daily_gift < date("Y-m-d")){
								$daily_gift_model = new DailyGiftModel();
								$list_gift = $daily_gift_model->getDailyGift($params);
								if (!empty($list_gift) && count($list_gift)) {
									foreach($list_gift as $item){
										$user_model->update(array("user_gome"=>new Zend_Db_Expr("user_gome + ".$item['zegome_gold']),
												"daily_gift"=>date("Y-m-d")), "user_id = ".$user->user_id);
										$this->__updateSession();
										$array = array(
												"zegome_gold"=>$item['zegome_gold'],
												"message"=>$item['message']);
										$daily_gift[] = $array;
									}
								}
							}
							if(!empty($daily_gift)){
								$content['daily_gift'] = $daily_gift;
							}else{
								$content['daily_gift'] = "Không có quà tặng";
							}
							$data['content'] = $content;
						} else {
							$data=array("code"=>0,
									"content"=>"Authentication failed");
						}
					} else {
						$data=array("code"=>0,
								"content"=>$message);
					}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}

	// cần gửi lên gift_id
	public function confirmGiftAction()
	{
		// Load model can thiet
		Zend_Loader::loadClass("UserModel");
		Zend_Loader::loadClass("GiftModel");

		//Lay va xu ly tham so
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (!empty($params['gift_id'])) {
				try {
					if ($this->_user) { // Đã đăng nhập
						// Xu ly o day
						$model_gift = new GiftModel();
						$gift = $model_gift->getItem(array("id"=>$params['gift_id']));
						if($gift['status'] == 1){
							$data = array("status" => 0, );
							$model_gift->update($data, "id = " . $params['gift_id']);
							if(!empty($gift['zegome_gold'])){
								$model_user = new UserModel();
								$model_user->update(array("user_gome"=>new Zend_Db_Expr("user_gome + ".$gift['zegome_gold'])), "user_id=".$this->_user->user_id);
							}
							$data=array("code"=>1,
									"content"=>"Success");
						}else{
							$data=array("code"=>0,
									"content"=>"Gift had used");
						}

					} else {
						$data=array("code"=>0,
								"content"=>"Authentication failed");
					}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}

	public function logoutAction()
	{
		$auth = new Service_Auth();
		$auth->logout();
		exit();
	}

	public function createTransactionAction()
	{
		//      Load cac model can thiet
		Zend_Loader::loadClass('UserModel');
		Zend_Loader::loadClass('RandomStringModel');
		Zend_Loader::loadClass('TransactionModel');

		$user_model = new UserModel();
		$transaction_model = new TransactionModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (isset($params['game_id']) && !empty($params['platform'])) {
				try {
					if (!empty($this->_user)) {
						$user = $user_model->getUserById($this->_user->user_id);
						if (!empty($user) && count($user)) {
							$transaction_id = RandomStringModel::make_token(16);
							$data = array(
									"transaction_id" => $transaction_id,
									"user_id" => $user['user_id'],
									"game_id" => $params['game_id'],
									"status" => 1,
									"created_time" => date("Y-m-d H:i:s")
							);
							$transaction_model->insert($data);
							$data=array("code"=>1,
									"content"=>array("transaction_id"=>$transaction_id));
						} else {
							$data=array("code"=>0,
									"content"=>"Invalid user");
						}
					} else {
						$data=array("code"=>0,
								"content"=>"Authentication failed");
					}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}

	public function finishTransactionAction()
	{
		//      Load cac model can thiet
		Zend_Loader::loadClass('UserModel');
		Zend_Loader::loadClass('TransactionModel');
		Zend_Loader::loadClass('PromotionEventModel');

		$user_model = new UserModel();
		$transaction_model = new TransactionModel();
		$promotion_model = new PromotionEventModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (!empty($params['transaction_id']) && isset($params['code']) && !empty($params['message'])) {
				try {
					if (!empty($this->_user)) {
						$transaction = $transaction_model->getTransaction($params);
						if ($transaction) {
							if ($params['code'] == 1) {
								$tran_array = explode("|", $params['message']);
								$transaction_id = $tran_array[0];
								$money = $tran_array[1];
								$currency = $tran_array[2];
								$promotion = $this->__getPromotion($this->_user->user_id);
								if (!empty($promotion) && count($promotion)) {
									$money = $money * (100 + $promotion['promotion']) / 100;
								}
								$where = "transaction_id = '" . $params['transaction_id'] . "'";
								$transaction_model->update(array("status" => 0, "updated_time" => date("Y-m-d H:i:s")), $where);
								$user_model->update(array("user_gome" => new Zend_Db_Expr("user_gome + " . $money)),
										"user_id = " . $transaction['user_id']);
							}
							$this->__updateSession();
							$user = $user_model->getUserById($this->_user->user_id);
							$data=array("code"=>1,
									"content"=>array("user_gome"=>$user['user_gome']));
						} else {
							$data=array("code"=>0,
									"content"=>"Transaction error");
						}
					} else {
						$data=array("code"=>0,
								"content"=>"Authentication failed");
					}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}

	public function chargeMoneyAction()
	{
        $params = $this->_arrParam;
        Zend_Loader::loadClass('TransactionModel');
		$transaction_model = new TransactionModel();
        $transaction_model->updateAppota($params);
		exit("ok");
	}

	public function useCouponAction()
	{
		//      Load cac model can thiet
		Zend_Loader::loadClass('UserModel');
		Zend_Loader::loadClass('CouponModel');

		$user_model = new UserModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (!empty($params['coupon_value'])) {
				try {
					if (!empty($this->_user)) {
						$coupon_model = new CouponModel();
						$result = $coupon_model->getCoupon($params);
						$where = "user_id = ".$this->_user->user_id;
						if (!empty($result)) {
							switch ($result['code']) {
								case "1":
									$money = 15000;
									break;
								case "2":
									$money = 30000;
									break;
								case "5":
									$money = 75000;
									break;
								case "10":
									$money = 150000;
									break;
								default:
									$money = 15000;
									break;
							}
							$user_model->update(array("user_gome" => new Zend_Db_Expr("user_gome + " . $money)),
									$where);
							$coupon_model->update(array("status" => 0,
									"use_user" => $this->_user->user_id,
									"use_time" => date("Y-m-d H:i:s",time())), "id=" . $result['id']);
							$user = $user_model->getUserById($this->_user->user_id);
							$data=array("code"=>1,
									"content"=>array("user_gome"=>$user['user_gome']));
						} else {
							$user = $user_model->getUserById($this->_user->user_id);
							if ($user['wrong_coupon_day'] == date("Y-m-d")) {
								$user_model->update(array("wrong_coupon" => new Zend_Db_Expr("wrong_coupon + 1")),
										$where);
							} else {
								$user_model->update(array("wrong_coupon" => 1, "wrong_coupon_day" => date("Y-m-d")),
										$where);
							}
							$message = "Invalid coupon";
							// cap nhat luot block
							$user = $user_model->getUserById($this->_user->user_id);
							if ($user['wrong_coupon'] >= 3) {
								if ($user['block_month'] == date("Y-m")) { // xet xem lan block nay co cung mot thang ko?
									$user_model->update(array(
											"status" => BLOCK_STATUS,
											"active_time" => time() + 86400,
											"number_block" => new Zend_Db_Expr("number_block + 1")), $where);
								} else {
									$user_model->update(array(
											"status" => BLOCK_STATUS,
											"active_time" => time() + 86400,
											"number_block" => 1,
											"block_month" => date("Y-m")), $where);
								}
								$auth = new Service_Auth();
								$auth->logout();
								$message = "Enter invalid coupon over 3 times. This account is temporarily blocked";
							}
							// xet xem co bi xoa vinh vien
							$user = $user_model->getUserById($this->_user->user_id);
							if ($user['number_block'] >= 3) {
								$user_model->update(array("status" => DELETE_FOREVER_STATUS), $where);
								$user_model->addBlacklist($user);
								$message = "Blocked over 3 times. This account has been permanently deleted";
							}
							$data=array("code"=>0,
									"content"=>$message);
						}
					} else {
						$data=array("code"=>0,
								"content"=>"Authentication failed");
					}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}

	// thiennx
	function __getPromotion($userId)
	{
		Zend_Loader::loadClass('PromotionEventModel');
		$promotionModel = new PromotionEventModel();
		$result = $promotionModel->getPromotion($userId);
		return $result;
	}

	public function getOpponientAction()
	{
		Zend_Loader::loadClass("SystemUserModel");
		Zend_Loader::loadClass("UserModel");
		$systemUserModel = new SystemUserModel();
		$user_model = new UserModel();
		$params = $this->_arrParam;
		$gome = isset($params["gome"]) ? $params["gome"] : 0;
		try {
			if (!empty($this->_user)) {
				if($this->_user->user_gome < $gome)
					$data=array("code"=>0,
							"content"=>"Can not find opponient");
				else{
					$user = (object)$user_model->getUserInfo(array('user_id' => $this->_user->user_id, 'game_id' => $params['game_id']));
					$systemUser = $systemUserModel->getOpponient(array("level" => $user->level, "gome" => $gome, 'game_id' => $params['game_id']));
					if ($systemUser){
						$data=array("code"=>1,
								"content"=>array("user_name"=>$systemUser['user_name'],
										"avatar"=>$systemUser['avatar'],
										"level"=>$systemUser['level'],
										"experiment" => $systemUser['experiment'],
										"achievement" => $this->mapCapdo[$systemUser["achievement_id"]]['name'],
										"star" => $systemUser["star"],
										"max_star" => $this->mapCapdo[$systemUser["achievement_id"]]['max_star'],
										"total_win" => $systemUser["total_win"],
										"total_lose" => $systemUser["total_lose"],
										"user_gome"=>$systemUser['user_gome'] - $gome));
						$user_model->update(array("user_gome" => $this->_user->user_gome - $gome), "user_id = ". $this->_user->user_id);
						$systemUserModel->update(array("user_gome" => $systemUser['user_gome'] - $gome), "id = ". $systemUser['id']);
						$this->__updateSession();
					}else
						$data=array("code"=>0,
								"content"=>"Can not find opponient");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Authentication failed");
			}
		}catch (exception $e){
			$data=array("code"=>0,
					"content"=>"Error in server");
		}
		echo json_encode($data);
		exit();
	}
	//thiennx
	public function updateResultAction(){
			
		Zend_Loader::loadClass('UserModel');
		Zend_Loader::loadClass('SystemUserModel');
		$user_model = new UserModel();
		$sys_user_model = new SystemUserModel();
		$params = $this->_arrParam;
		$coupon_gift = 0;
		//Zend_Debug::dump($params);
		if($this->_request->isPost()){
			try {
				if (!empty($this->_user)) {
					if(!empty($params["opponient"]) && !empty($params["result"]) && isset($params["gome"]) && !empty($params["game_id"])){
						$s_user = $sys_user_model->findUserByName($params["opponient"], $params["game_id"]);
						$this->_user = (object) $user_model->getUserInfo(array("user_id" => $this->_user->user_id, "game_id" => $params["game_id"]));
						$return = array();
						//tính công thức cộng kinh nghiệm vs 1 ván thắng
						//tính theo cấp độ user
						$userExpBonus = 5*($this->_user->achievement_id * $this->_user->achievement_id - $this->_user->achievement_id + $this->_user->level +3 );
						$oppExpBonus = 5*($s_user["achievement_id"] * $s_user["achievement_id"] - $s_user["achievement_id"] + $s_user["level"] +3 );
						switch ($params["result"]){
							case 1: // user thắng
								//cập nhật user
								$userNewExp = round( $this->_user->experiment + $oppExpBonus * (($this->_user->win + 1) == 3 ? 1.2 :1)) ;
								$newLevel = $this->__caculateLevel($this->_user->achievement_id,$this->_user->level, $userNewExp, 1);
								$level_down = $this->_user->level_down - $newLevel["thangcap"];
								
								if($level_down < 0) { $level_down =0; $coupon_gift = 1;}
								
								$data = array(
										"level" => $newLevel["level"],
										"experiment" => $userNewExp,
										"achievement_id" => $newLevel["capdoId"],
										"level_down" => $level_down,
										"star" => $newLevel["star"],
										"win" => $this->_user->win + 1,
										"total_win" => $this->_user->total_win + 1,
										"lose" => 0,
										"user_gome" => $this->_user->user_gome + round($params["gome"]*1.85)
								);
								$user_model->updateInfo($data, $this->_user->user_id, $params["game_id"]);
								//cập nhật opponient
								$direct = 1;
								if($s_user["lose"]+1 == 3 ){ // nếu thua ba trận liên tiếp trừ 20% kn tương ứng cấp độ của mình
									$opponientNewExp = $s_user["experiment"] - 0.2 * $oppExpBonus;
									$direct = -1;
								}
								else if($s_user["achievement_id"] == $this->_user->achievement_id) // thua bang cap do thi ko cong
									$opponientNewExp = $s_user["experiment"];
								else if($s_user["achievement_id"] > $this->_user->achievement_id){ // thua thằng kem cap do thi tru 10 % cua no
									$opponientNewExp = $s_user["experiment"] - 0.1 * $userExpBonus;
									$direct = -1;
								}
								else //thua thang hon cap do thi cong 20% cua minh
									$opponientNewExp = $s_user["experiment"] + 0.2 * $oppExpBonus;
								$opponientNewExp = round($opponientNewExp);
									
								if($opponientNewExp <0) $opponientNewExp = 0;
								$oppNewLevel = $this->__caculateLevel($s_user["achievement_id"],$s_user["level"], $opponientNewExp, $direct);
								$data = array(
										"level" => $oppNewLevel["level"],
										"experiment" => $opponientNewExp,
										"achievement_id" => $oppNewLevel["capdoId"],
										"star" => $oppNewLevel["star"],
										"win" => 0,
										"lose" => $s_user["lose"] +1,
										"total_lose" => $s_user["total_lose"] +1,
										"user_gome" => $s_user["user_gome"]
								);
								$sys_user_model->updateInfo($data, $params["opponient"], $params["game_id"]);
								$return = array(
										"code" => 1,
										"content" => array(
												"user" => array(
														"level" => $newLevel["level"],
														"experiment" => $userNewExp,
														"experiment_up" => $userNewExp - $this->_user->experiment,
														"achievement" => $newLevel["capdo"],
														"thangcap" => $newLevel["thangcap"],
														"star" => $newLevel["star"],
														"max_star" => $newLevel["max_star"],
														"level_up" => $newLevel["level_up"],
														"user_gome" => $this->_user->user_gome + round($params["gome"]*1.85),
														"user_gome_recieved" => round($params["gome"]*1.85)
												),
												"opponient" => array(
														"level" => $oppNewLevel["level"],
														"experiment" => $opponientNewExp,
														"experiment_up" => $opponientNewExp - $s_user["experiment"],
														"achievement" => $oppNewLevel["capdo"],
														"thangcap" => $oppNewLevel["thangcap"],
														"star" => $oppNewLevel["star"],
														"max_star" => $oppNewLevel["max_star"],
														"level_up" => $oppNewLevel["level_up"],
														"user_gome" => $s_user["user_gome"],
														"user_gome_recieved" => 0
												)
										)
								);
								break;
							case 2 : //hòa
								//cập nhật user
								$userNewExp = round($this->_user->experiment + 0.3 * $oppExpBonus);
								$newLevel = $this->__caculateLevel($this->_user->achievement_id,$this->_user->level, $userNewExp, 1);
								$level_down = $this->_user->level_down - $newLevel["thangcap"];
								if($level_down < 0) { $level_down =0; $coupon_gift = 1;}
								$data = array(
										"level" => $newLevel["level"],
										"experiment" => $userNewExp,
										"achievement_id" => $newLevel["capdoId"],
										"level_down" => $level_down,
										"star" => $newLevel["star"],
										"user_gome" => $this->_user->user_gome + round( $params["gome"] * 0.925)
								);
								$user_model->updateInfo($data, $this->_user->user_id, $params["game_id"]);
								//cập nhật opponient
								$opponientNewExp = round($s_user["experiment"] + 0.3 * $userExpBonus);
								$oppNewLevel = $this->__caculateLevel($s_user["achievement_id"],$s_user["level"], $opponientNewExp, 1);
								$data = array(
										"level" => $oppNewLevel["level"],
										"experiment" => $opponientNewExp,
										"achievement_id" => $oppNewLevel["capdoId"],
										"star" => $oppNewLevel["star"],
										"user_gome" => $s_user["user_gome"] + round( $params["gome"] * 0.925)
								);
								$sys_user_model->updateInfo($data, $params["opponient"], $params["game_id"]);
								$return = array(
										"code" => 1,
										"content" => array(
												"user" => array(
														"level" => $newLevel["level"],
														"experiment" => $userNewExp,
														"experiment_up" => $userNewExp - $this->_user->experiment,
														"achievement" => $newLevel["capdo"],
														"thangcap" => $newLevel["thangcap"],
														"star" => $newLevel["star"],
														"max_star" => $newLevel["max_star"],
														"level_up" => $newLevel["level_up"],
														"user_gome" => $this->_user["user_gome"] + round( $params["gome"] * 0.925),
														"user_gome_recieved" => round( $params["gome"] * 0.925)
														
												),
												"opponient" => array(
														"level" => $oppNewLevel["level"],
														"experiment" => $opponientNewExp,
														"experiment_up" => $opponientNewExp - $s_user["experiment"],
														"achievement" => $oppNewLevel["capdo"],
														"thangcap" => $oppNewLevel["thangcap"],
														"star" => $oppNewLevel["star"],
														"max_star" => $oppNewLevel["max_star"],
														"level_up" => $oppNewLevel["level_up"],
														"user_gome" => $s_user["user_gome"] + round( $params["gome"] * 0.925),
														"user_gome_recieved" => round( $params["gome"] * 0.925)
												)
										)
								);
								break;
							case 3 : //user thua
								//cập nhật user
								$direct = 1;
								if($this->_user->lose +1 == 3 ){ // nếu thua ba trận liên tiếp trừ 20% kn tương ứng cấp độ của mình
									$userNewExp = $this->_user->experiment - 0.2 * $userExpBonus;
									$direct = -1;
								}
								else if($s_user["achievement_id"] == $this->_user->achievement_id) // thua bang cap do thi ko cong
									$userNewExp = $this->_user->experiment;
								else if($s_user["achievement_id"] < $this->_user->achievement_id){ // thua thằng kem cap do thi tru 10 % cua no
									$userNewExp = $this->_user->experiment - 0.1 * $oppExpBonus;
									$direct = -1;
								}
								else //thua thang hon cap do thi cong 20% cua minh
									$userNewExp = $this->_user->experiment + 0.2 * $userExpBonus;
								$userNewExp = round($userNewExp);
								if($userNewExp < 0) $userNewExp =0;
								$newLevel = $this->__caculateLevel($this->_user->achievement_id,$this->_user->level, $userNewExp, $direct);
								$level_down = $this->_user->level_down - $newLevel["thangcap"];
								if($level_down < 0) { $level_down =0; $coupon_gift = 1;}
								$data = array(
										"level" => $newLevel["level"],
										"experiment" => $userNewExp,
										"achievement_id" => $newLevel["capdoId"],
										"level_down" => $level_down,
										"star" => $newLevel["star"],
										"lose" => $this->_user->lose + 1,
										"total_lose" => $this->_user->total_lose + 1,
										"win" => 0,
								);
								$user_model->updateInfo($data, $this->_user->user_id, $params["game_id"]);
								//cập nhật opponient
								$opponientNewExp = round( $s_user["experiment"] + $userExpBonus * (($s_user['win'] + 1) == 3 ? 1.2 :1)) ;
								$oppNewLevel = $this->__caculateLevel($s_user["achievement_id"],$s_user["level"], $opponientNewExp, 1);
								$where = "user_name = '". $params["opponient"]."'";
								$data = array(
										"level" => $oppNewLevel["level"],
										"experiment" => $opponientNewExp,
										"achievement_id" => $oppNewLevel["capdoId"],
										"star" => $oppNewLevel["star"],
										"lose" => 0,
										"win" => $s_user["win"] +1,
										"total_win" => $s_user["total_win"] +1,
										"user_gome" => $s_user["user_gome"] + round( $params["gome"] * 1.85)
								);
								$sys_user_model->updateInfo($data, $params["opponient"], $params["game_id"]);
								$return = array(
										"code" => 1,
										"content" => array(
												"user" => array(
														"level" => $newLevel["level"],
														"experiment" => $userNewExp,
														"experiment_up" => $userNewExp - $this->_user->experiment,
														"achievement" => $newLevel["capdo"],
														"thangcap" => $newLevel["thangcap"],
														"star" => $newLevel["star"],
														"max_star" => $newLevel["max_star"],
														"level_up" => $newLevel["level_up"],
														"user_gome" => $this->_user->user_gome,
														"user_gome_recieved" => 0
												),
												"opponient" => array(
														"level" => $oppNewLevel["level"],
														"experiment" => $opponientNewExp,
														"experiment_up" => $opponientNewExp - $s_user["experiment"],
														"achievement" => $oppNewLevel["capdo"],
														"thangcap" => $oppNewLevel["thangcap"],
														"star" => $oppNewLevel["star"],
														"max_star" => $oppNewLevel["max_star"],
														"level_up" => $oppNewLevel["level_up"],
														"user_gome" => $s_user["user_gome"] + round( $params["gome"] * 1.85),
														"user_gome_recieved" => round( $params["gome"] * 1.85)
												)
										)
								);
								break;
						}
						//cập nhật lại user lưu vào session
						$this->__updateSession();
						// đã cập nhật thông tin mới nhất cho user vào session nên $this->_user->user_gome giờ là giá trị mới
						$return["content"]["user"]["user_gome"] = $this->_user->user_gome; // trả về thêm user_gome
						//nếu thăng cấp tặng coupon
						Zend_Loader::loadClass("CouponModel");
						$modelCopon = new CouponModel();
						if($coupon_gift){
							
							
							do{
								$coupon = $this->__generateRandomString(13);
								
							}
							while (!$modelCopon->validateCoupon($coupon));
							$modelCopon->insert(array(
									"value" => $coupon,
									"code" => 1,
									"start_time" => date("Y-m-d H:i:s", time()),
									"end_time" => date("Y-m-d H:i:s", time() + 560000),
									"create_user" => "system",
									"receive_user" => $this->_user->user_id
							));
							$return["content"]["user"]["coupon"] = $coupon;
						}
						else $return["content"]["user"]["coupon"]= null;
					}
					else {
						$return = array(
								"code" => 0,
								"content" => "Invalid parameters"
						);
					}
				}else{
					$return = array(
							"code" => 0,
							"content" => "Authentication failed"
					);
				}
			}
			catch (exception $e){
				$return=array("code"=>0,
						"content"=>"Error in server");
			}
			echo json_encode($return);
		}
		exit();
	}
	public function __caculateLevel($capdo,$level, $experient, $direct){
		$mapLevel = array(
				1 => "0",
				2 => "100",
				3 => "350",
				4 => "950",
				5 => "2300",
				6 => "4300",
				7 => "7050",
				8 => "10650",
				9 => "16600",
				10 => "23800",
				11 => "32350",
				12 => "42350",
				13 => "53900",
				14 => "69500",
				15 => "87050",
				16 => "106650",
				17 => "128400",
				18 => "152400",
				19 => "178750",
				20 => "207550",
				21 => "246500",
				22 => "288500",
				23 => "333650",
				24 => "382050",
				25 => "433800",
				26 => "489000",
				27 => "547750",
				28 => "610150"
		);
		$mapCapdo = $this->mapCapdo;
		for($i = $level; $i>=1 ; $i = $i + $direct){
			if($mapLevel[$i] <= $experient && (!isset($mapLevel[$i+1]) || $mapLevel[$i+1] > $experient))
				break;
		}
		// new level : $i
		for($j = $capdo; $j>=1 ; $j = $j + $direct){
			if($mapCapdo[$j]['level'] <= $i && (!isset($mapCapdo[$j+1]) || $mapCapdo[$j+1]['level'] > $i))
				break;
		}
		return array(
				"level" => $i,
				"level_up" => $i - $level,
				"capdoId" => $j,
				"capdo" => $mapCapdo[$j]["name"],
				"max_star" => $mapCapdo[$j]["max_star"],
				"thangcap" => $j - $capdo,
				"star" => $i - $mapCapdo[$j]['level'] +1
		);
	}
	public function __updateSession(){
		Zend_Loader::loadClass('UserModel');
		$model = new UserModel();
		if($this->_user){
			$user = $model->fetchRow("user_id= ".$this->_user->user_id)->toArray();
			unset($user['password']);

			$std_user = new stdClass();

			foreach ($user as $key => $value)
			{
				$std_user->$key = $value;
			}
			$auth = Zend_Auth::getInstance();
			$auth->getStorage()->write($std_user);
			$this->_user = $std_user;
		}
	}
	public function saveMailAction(){
		//      Load cac model can thiet
		Zend_Loader::loadClass('MailModel');

		$model = new MailModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (!empty($params['mail'])) {
				try {
					$result = $model->check($params['mail']);
					if(!$result){
						$model->insert(array("mail" => $params['mail']));
					}	
				}
				catch (exception $e){
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}
	public function saveAvatarAction(){
		//      Load cac model can thiet
		Zend_Loader::loadClass('UserModel');

		$user_model = new UserModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (!empty($params['avatar'])) {
				
				try {
					if (!empty($this->_user)) {
						$user = $user_model->getUserById($this->_user->user_id);
						$avatar = $this->__base64_to_jpeg($params['avatar'], "public/avatar/".$user['user_name']."_avatar".".png");
						if (!empty($user) && count($user)) {
							$where = "user_id = ".$user['user_id'];
							$time_update_avatar = date("Y-m-d H:i:s");
							$user_model->update(array("avatar"=>$avatar,
									"time_update_avatar"=>$time_update_avatar), $where);
							$data=array("code"=>1,
									"content"=>array("time_update"=>$time_update_avatar,
											"avatar" => $avatar
									));
						} else {
							$data=array("code"=>0,
									"content"=>"Invalid user");
						}
					} else {
						$data=array("code"=>0,
								"content"=>"Authentication failed");
					}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}

	public function getAvatarAction(){
		//      Load cac model can thiet
		Zend_Loader::loadClass('UserModel');

		$user_model = new UserModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			if (!empty($params['time_update_avatar'])) {
				try {
					if (!empty($this->_user)) {
						$user = $user_model->getUserById($this->_user->user_id);
						if (!empty($user) && count($user)) {
							$params['time_update_avatar'] = str_replace("%20", " ", $params['time_update_avatar']);
							if($user['time_update_avatar'] != $params['time_update_avatar']){
								$data=array("code"=>1,
										"content"=>array("time_update"=>$user['time_update_avatar'],
												"avatar"=>$user['avatar']));
							}else{
								$data=array("code"=>0,
										"content"=>"Avatar is not changed");
							}
						} else {
							$data=array("code"=>0,
									"content"=>"Invalid user");
						}
					} else {
						$data=array("code"=>0,
								"content"=>"Authentication failed");
					}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
			} else {
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
			echo json_encode($data);
		}
		exit();
	}
	public function getVersionAction(){
		$params = $this->_arrParam;
		Zend_Loader::loadClass("GameModel");
		if(isset($params["game_id"])){
			$model = new GameModel();
			$result = $model->getVersion($params["game_id"]);
			if($result){
				$data = array("code" => 1,
							"content" => $result
				);
			}else{
				$data = array("code" => 0,
						"content" => "Game not found"
						);
			}
		}else{
			$data=array("code"=>0,
					"content"=>"Invalid parameters");
		}
		echo json_encode($data);
		exit();
	}
	public function getNoticeAction(){
		//      Load cac model can thiet
		Zend_Loader::loadClass('MessageModel');
		Zend_Loader::loadClass('AdvertiseModel');
		$params = $this->_arrParam;
		try {
			// Kiem tra hop qua tang xem co tin nhan ko?
			$message_model = new MessageModel();
			$list_message = $message_model->getList(null);
			$content = array();
			$message = array();
			$count_message = count($list_message);
			if (!empty($list_message) && $count_message) {
				foreach($list_message as $item){
					$message[] = array("message_content"=>$item['message'], "message_eng" => $item["message_eng"]);
				}
				
			}
			$content["message"] = $message;
			$advertise_model = new AdvertiseModel();
			$list_advertise = $advertise_model->getList();
			$advertise = array();
			if (!empty($list_advertise) && count($list_advertise)) {
				foreach($list_advertise as $item){
					$advertise[] = array(
							"icon"=>$item['icon'],
							"link" => $item["link"],
							"message_vn" => $item["message_vn"],
							"message_eng" => $item["message_eng"],
					);
				}		
		}
		$content['advertise'] = $advertise;
		$data=array("code"=>1,
				"content"=>$content);
		}
		catch (exception $e) {
			$data=array("code"=>0,
					"content"=>"Error in server");
		}
		echo json_encode($data);
		exit();
	}
	public function getAdvertiseAction(){
		Zend_Loader::loadClass('AdvertiseModel');
		try{
			$advertise_model = new AdvertiseModel();
			$list_advertise = $advertise_model->getList();
			$advertise = array();
			if (!empty($list_advertise) && count($list_advertise)) {
				foreach($list_advertise as $item){
					$advertise[] = array(
							"icon"=>$item['icon'],
							"link" => $item["link"],
							"message_vn" => $item["message_vn"],
							"message_eng" => $item["message_eng"],
					);
				}
				$content['advertise'] = $advertise;
				$data=array("code"=>1,
						"content"=>$content);
			}
			else{
				$data=array("code"=>0,
						"content"=>"No advertise");
			}
		}catch (exception $e) {
			$data=array("code"=>0,
					"content"=>"Error in server");
		}
		echo json_encode($data);
		exit();
	}
	public function getGoldAction(){
		//      Load cac model can thiet
		Zend_Loader::loadClass('UserModel');

		$user_model = new UserModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			try {
				if (!empty($this->_user)) {
					$user = $user_model->getUserById($this->_user->user_id);
					if (!empty($user) && count($user)) {
						$data=array("code"=>1,
								"content"=>array("user_gome"=>$user['user_gome']));
					} else {
						$data=array("code"=>0,
								"content"=>"Invalid user");
					}
				} else {
					$data=array("code"=>0,
							"content"=>"Authentication failed");
				}
			}
			catch (exception $e) {
				$data=array("code"=>0,
						"content"=>"Error in server");
			}
			echo json_encode($data);
		}
		exit();
	}
	public function addGomeAction(){
		Zend_Loader::loadClass('UserModel');
		
		$user_model = new UserModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			try {
				if (!empty($this->_user)) {
					$user = $user_model->getUserById($this->_user->user_id);
					if (!empty($user) && count($user)) {
						if($user['user_gome']+$params["gome"]>=0){
							$user_model->update(array("user_gome" => $user['user_gome']+$params["gome"]), "user_id = ".$this->_user->user_id);
							$data=array("code"=>1,
								"content"=>array("user_gome"=>$user['user_gome']+$params["gome"]));
						}
						else{
							$data=array("code"=>0,
									"content"=>"Not enough gome");
						}
					} else {
						$data=array("code"=>0,
								"content"=>"Invalid user");
					}
				} else {
					$data=array("code"=>0,
							"content"=>"Authentication failed");
				}
				}
				catch (exception $e) {
					$data=array("code"=>0,
							"content"=>"Error in server");
				}
				echo json_encode($data);
		}
		exit();
	}
	public function getTopuserAction(){
		//      Load cac model can thiet
		Zend_Loader::loadClass('UserModel');
		$params = $this->_arrParam;
		try {
			// Kiem tra hop qua tang xem co tin nhan ko?
			if(!empty($params['limit'])){
				$user_model = new UserModel();
				$list_top_user = $user_model->getListTopUser($params['limit'], $params["game_id"]);
				$top_user = array();
				$count_top_user = count($list_top_user);
				if (!empty($list_top_user) && $count_top_user) {
					foreach($list_top_user as &$item){
						$item["achievement"] = $this->mapCapdo[$item["achievement_id"]]['name'];
						$item["user_name"] = $item["user_name"] ? $item["user_name"] : $item["sys_user_name"];
						unset($item["achievement_id"]);
						unset($item["sys_user_name"]);
						// 						$top_user[] = array(
						// 								"stt"=>$item['id'],
						// 								"user_id"=>$item['user_id'],
						// 								"user_name"=>$item['user_name'],
						// 								"level"=>$item['level'],
						// 								"experiment"=>$item['experiment']);
					}
					$data=array("code"=>1,
							"content"=>array("top_user"=>$list_top_user));
				}else{
					$data=array("code"=>0,
							"content"=>"Data not found");
				}
			}else{
				$data=array("code"=>0,
						"content"=>"Invalid parameters");
			}
		}
		catch (exception $e) {
			$data=array("code"=>0,
					"content"=>"Error in server");
		}
		echo json_encode($data);
		exit();
	}
	//hàm thưởng kinh nghiệm cho user
	function bonusExperimentAction(){
		Zend_Loader::loadClass('UserModel');
		$user_model = new UserModel();
		$params = $this->_arrParam;
		if($this->_request->isPost()){
			try {
				$user = (object) $user_model->getUserInfo(array("user_id" => $this->_user->user_id, "game_id" => $params["game_id"]));

				if($params["type"] == 1 || $params["type"] == 3) // cộng 50 exp
					$newExp = $user->experiment + 50;
				else if($params["type"] ==2){
					$newExp = $user->experiment + round($params["money"]/1000);
				}else exit();
				if(isset($newExp)){
					$newLevel = $this->__caculateLevel($user->achievement_id,$user->level, $newExp, 1);
					$data = array(
							"level" => $newLevel["level"],
							"experiment" => $newExp,
							"achievement_id" => $newLevel["capdoId"],
							"star" => $newLevel["star"],
					);
					$user_model->updateInfo($data, $this->_user->user_id, $params["game_id"]);
					$return = array(
							"code" => 1,
							"content" => array(
									"level" => $newLevel["level"],
									"experiment" => $newExp,
									"experiment_recieved" => $newExp - $user->experiment,
									"achievement" => $newLevel["capdo"],
									"thangcap" => $newLevel["thangcap"],
									"star" => $newLevel["star"],
									"max_star" => $newLevel["max_star"],
									"level_up" => $newLevel["level_up"]

							));
				}
			}catch (Exception $e){
				$return=array("code"=>0,
						"content"=>"Error in server");
			}
			echo json_encode($return);
		}
		exit();
	}
	private function __base64_to_jpeg($base64_string, $output_file) {
		$ifp = fopen($output_file, "wb");

		fwrite($ifp, base64_decode($base64_string));
		
		fclose($ifp);

		return $output_file;
	}
	public function __generateRandomString($length = 13) {
		return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
	}
}
